package com.github.rxyor.common.support.util;

import com.github.rxyor.common.core.exception.CoreException;
import com.github.rxyor.common.util.security.SafeSignVerifyUtil;
import java.io.UnsupportedEncodingException;
import org.apache.commons.lang3.StringUtils;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2019/11/7 周四 16:15:00
 * @since 1.0.0
 */
public class CryptoUtil {

    public final static String REQUEST_PARAM_CONST_KEY = "crypto_api_sign";
    private final static String DEFAULT_USERNAME = "R3JpbEZyaWVuZA==";
    private final static String DEFAULT_PASSWORD = "ZmlyZWZseQ==";

    public static String sign(Long expire) {
        if (expire == null || expire <= 0) {
            throw new IllegalArgumentException("签名时长无效, 有效的签名时长必须大于0");
        }
        SafeSignVerifyUtil instance = SafeSignVerifyUtil.builder()
            .expire(expire)
            .username(DEFAULT_USERNAME)
            .password(DEFAULT_PASSWORD)
            .build();
        return instance.sign();
    }

    public static String urlEncodeSign(Long expire) {
        try {
            return java.net.URLEncoder.encode(sign(expire), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new CoreException(e);
        }
    }

    public static Boolean verify(String cryptoString) {
        if (StringUtils.isBlank(cryptoString)) {
            throw new IllegalArgumentException("签名无效");
        }
        SafeSignVerifyUtil instance = SafeSignVerifyUtil.builder()
            .username(DEFAULT_USERNAME)
            .password(DEFAULT_PASSWORD)
            .build();
        try {
            return instance.verify(cryptoString);
        } catch (Exception e) {
            return false;
        }
    }

}
